//
//  MailDetail.m
//  Speedater
//
//  Created by NgoThang on 1/3/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MailDetail.h"
#import "Start.h"
#import "MailCompose.h"
#import "ContactDetail.h"
#import "AppDelegate.h"
#import "asyncimageview.h"
#import "JSON.h"

@interface MailDetail (Private)

- (void)cleanup;

@end

@implementation MailDetail (Private)

- (void)cleanup 
{
    self.myTabBar = nil;
    self.avatarImageView = nil;
    self.nameAndSubjectLabel = nil;
    self.dateLabel = nil;
    self.bodyTextView = nil;
    self.replyButton = nil;
    self.removeButton = nil;
    self.mailDetailId = nil;
    self.username = nil;
    self.subject = nil;
}

@end


@implementation MailDetail

@synthesize myTabBar;
@synthesize avatarImageView;
@synthesize nameAndSubjectLabel, dateLabel;
@synthesize bodyTextView;
@synthesize replyButton, removeButton;
@synthesize mailDetailId, username, subject;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    //NSLog(@"MAILDETAIL -> dealloc");
    [self cleanup];
    [super dealloc];
}

#pragma mark - Custom functions

- (IBAction)replyButtonClick:(id)sender
{
    MailCompose *mailCompose = [[MailCompose alloc] init];
    
    if ([username length]) {
        mailCompose.username = [NSString stringWithString:username];
    }
    
    if ([subject length]) {
        if ([subject rangeOfString:@"AWT:"].location==NSNotFound)
            mailCompose.subject = [NSString stringWithFormat:@"AWT: %@", subject];
        else
            mailCompose.subject = [NSString stringWithString:subject];
    }
    
    [self.navigationController pushViewController:mailCompose animated:YES];
    [mailCompose release];
}

- (IBAction)removeButtonClick:(id)sender
{
    UIAlertView *message = [[UIAlertView alloc] initWithTitle:nil
                                                      message:NSLocalizedString(@"Are you sure, you want to remove it?", nil)
                                                     delegate:self
                                            cancelButtonTitle:NSLocalizedString(@"Cancel", nil)
                                            otherButtonTitles:NSLocalizedString(NSLocalizedString(@"OK", nil), nil), nil];
    [message show];
    [message release];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex)
    {
        // set request mode
        requestMode = 2;
        
        NSString *postString = [NSString stringWithFormat:@"op=deleteMail&id=%@", mailDetailId];
        NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
        NSString *postLength = [NSString stringWithFormat:@"%d", [postString length]];
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"]]];
        
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setHTTPBody:postData];
        [request setTimeoutInterval:60.0];
        NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
        if (conn) {
            // init data    
            responseData = [[NSMutableData data ] retain];
            
            // loading
            UIWindow *theWindow = [UIApplication sharedApplication].keyWindow;
            HUD = [[MBProgressHUD alloc] initWithWindow:theWindow];
            [theWindow addSubview:HUD];
            HUD.delegate = self;
            [HUD show:YES];
        }
        [conn release];
        
    }
}

- (void)contactDetailClick 
{
    if (![username isEqualToString:[[NSUserDefaults standardUserDefaults] stringForKey:@"username"]]) {
        ContactDetail *contactDetail = [[ContactDetail alloc] init];
        NSString *fUsername = [[NSString alloc] initWithString:username];
        contactDetail.friendUsername = fUsername;
        [fUsername release];
        [[[[[self.tabBarController viewControllers] objectAtIndex:2] topViewController] navigationController] popToRootViewControllerAnimated:NO];
        [[[self.tabBarController viewControllers] objectAtIndex:2] pushViewController:contactDetail animated:YES];
        [contactDetail release];
        self.tabBarController.selectedIndex = 2;
    }
    else {
        UINavigationController *nav1 = [self.tabBarController.viewControllers objectAtIndex:0];
        for (UIViewController *vc in nav1.viewControllers)
            if ([vc isKindOfClass:[Start class]]){
                [nav1.topViewController.navigationController popToViewController:vc animated:NO];
                break;
            }
        [(Start *)[[self.tabBarController.viewControllers objectAtIndex:0] topViewController] editProfileButtonClick:NULL];
        self.tabBarController.selectedIndex = 0;
    }
}

- (void)loadMail
{
    // set request mode
    requestMode = 1;
    
    NSString *postString = [NSString stringWithFormat:@"op=loadMail&id=%@", mailDetailId];
    NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postString length]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"]]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];       
    [request setTimeoutInterval:60.0];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (conn) {
        // init data    
        responseData = [[NSMutableData data ] retain];
        
        // loading
        UIWindow *theWindow = [UIApplication sharedApplication].keyWindow;
        HUD = [[MBProgressHUD alloc] initWithWindow:theWindow];
        [theWindow addSubview:HUD];
        HUD.delegate = self;
        [HUD show:YES];
    }
    [conn release];
}

- (void)goStart
{
    // goto Start form
    self.tabBarController.selectedIndex = 0;
    
    UINavigationController *nav1 = [self.tabBarController.viewControllers objectAtIndex:0];
    for (UIViewController *vc in nav1.viewControllers)
        if ([vc isKindOfClass:[Start class]]){
            //NSLog(@"MAILDETAIL -> popToViewController: %@", vc);
            [nav1.topViewController.navigationController popToViewController:vc animated:YES];
            return;
        }
}

- (void)goBack
{
    // goto login form
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    //NSLog(@"MAILDETAIL -> viewDidLoad");
    [super viewDidLoad];
    
    // background
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    
    // navigation title
    self.title = @"Mail ansicht";
    
    // navigation buttons
    UIButton *logoButton = [[UIButton alloc] initWithFrame:CGRectMake(0,2,35,35)];
    [logoButton setBackgroundImage:[UIImage imageNamed:@"logo.png"] forState:UIControlStateNormal];
    [logoButton addTarget:self action:@selector(goStart) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *iLButton = [[UIBarButtonItem alloc] initWithCustomView:logoButton];
    self.navigationItem.leftBarButtonItem = iLButton;
    [logoButton release];
    [iLButton release];
    
    UIButton *backButton = [UIButton buttonWithType:100];
    [backButton setTitle:@"Zurück" forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *iRButton = [[UIBarButtonItem alloc] initWithCustomView: backButton];
    self.navigationItem.rightBarButtonItem = iRButton;
    [iRButton release];
    
    // selected tab
    [myTabBar setSelectedItem:[myTabBar.items objectAtIndex:2]];
    
    // add handler
    UITapGestureRecognizer *tgrContactDetail = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(contactDetailClick)] autorelease];
    [self.avatarImageView addGestureRecognizer:tgrContactDetail];
    UITapGestureRecognizer *tgrContactDetail1 = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(contactDetailClick)] autorelease];
    [self.nameAndSubjectLabel addGestureRecognizer:tgrContactDetail1];
    
    // mail detail id
    [[NSUserDefaults standardUserDefaults] setObject:mailDetailId forKey:@"mail_detail_id"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    // load mail detail
    [self loadMail];
}

- (void)viewDidUnload
{
    //NSLog(@"MAILDETAIL -> viewDidUnload");
    [self cleanup];
    [super viewDidUnload];
}
- (void)viewWillAppear:(BOOL)animated
{
    //NSLog(@"MAILDETAIL -> viewWillAppear");
    //NSLog(@"MAILDETAIL -> viewControllers: %@", self.navigationController.viewControllers);
    
    // save state
    [AppDelegate saveState:3 withViewController:self];
    
    // update tabbar
    [AppDelegate updateTabBarItem:myTabBar withMailValue:-1 andUpdateMute:NO];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    [myTabBar setSelectedItem:[myTabBar.items objectAtIndex:2]];
    switch (item.tag) {
        case 0:
            [[[[self.tabBarController.viewControllers objectAtIndex:1] topViewController] navigationController] popToRootViewControllerAnimated:NO];
            self.tabBarController.selectedIndex = 1;
            break;
        case 1:
            [[[[self.tabBarController.viewControllers objectAtIndex:2] topViewController] navigationController] popToRootViewControllerAnimated:NO];
            self.tabBarController.selectedIndex = 2;
            break;
        case 2: 
            break;
        case 3: 
            [AppDelegate updateTabBarItem:myTabBar withMailValue:-1 andUpdateMute:YES];
            break;
        default:
            break;
    }
}

#pragma mark -
#pragma mark NSURLConnectionDelegete

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{
	[responseData setLength:0];
    
    // loading
	HUD.mode = MBProgressHUDModeDeterminate;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{
    // loading
    [HUD hide:YES];
    
    /* Error message */
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
													message:NSLocalizedString(@"Unknown network error", nil)
												   delegate:self 
										  cancelButtonTitle:NSLocalizedString(@"OK", nil) 
										  otherButtonTitles:nil];
	[alert show];
	[alert release];	
    
    [responseData release];
    responseData = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	
	NSMutableDictionary *results = [responseString JSONValue];
    [responseString release];
    
    switch (requestMode) {
        case 1:
            username = [[results objectForKey:@"sender"] retain];
            subject = [results objectForKey:@"sub"];
            subject = [subject isEqualToString:@"(null)"]?@"":subject;
            subject = [[AppDelegate decodeText:subject] retain];

            // get avatar image
            AsyncImageView *asyncImage = [[AsyncImageView alloc] initWithFrame:CGRectMake(16, 10, 47, 43)];
            asyncImage.tag = 999;
            NSURL *avatarURL = [NSURL URLWithString: [NSString stringWithFormat:@"%@avatar/%@", 
                                                      [[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"], 
                                                      username]];
            [asyncImage loadImageFromURL:avatarURL];
            [asyncImage setForImage:avatarImageView];
            avatarImageView.contentMode = UIViewContentModeScaleAspectFit;
            [asyncImage release];
            
            
            [nameAndSubjectLabel setText:[NSString stringWithFormat:@"%@: %@",[results objectForKey:@"sender"], subject]];
            [dateLabel setText:[NSString stringWithFormat:@"Vom %@ um %@ Uhr",[results objectForKey:@"date"], [results objectForKey:@"time"]]];
            [bodyTextView setText:[AppDelegate decodeText:[results objectForKey:@"content"]]];
            
            break;
        case 2:
            if ([[results objectForKey:@"status"] isEqualToString:@"1"]) 
            {
                [self goBack];
                
                UIAlertView *alert = [[UIAlertView alloc] 
                                      initWithTitle:nil 
                                      message:NSLocalizedString(@"Remove successfully!", nil) 
                                      delegate:nil 
                                      cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                                      otherButtonTitles:nil];
                [alert show];	
                [alert release];
            }
            else 
            {
                UIAlertView *alert = [[UIAlertView alloc] 
                                      initWithTitle:nil 
                                      message:NSLocalizedString(@"Incidents occur, please check again!", nil) 
                                      delegate:nil 
                                      cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                                      otherButtonTitles:nil];
                [alert show];	
                [alert release];
            }
            
            break;
        default:
            break;
    }
    
    [responseData release];
    responseData = nil;
    
    // loading
    [HUD hide:YES];
}

#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden:(MBProgressHUD *)hud {
    // Remove HUD from screen when the HUD was hidded
    [HUD removeFromSuperview];
    [HUD release];
    HUD = nil;
}

@end
